package top.gytf.unifiedcall.common.util;

import cn.hutool.core.lang.Assert;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import top.gytf.unifiedcall.model.code.Code;

/**
 * 编码工具类
 *
 * @see top.gytf.unifiedcall.model.code.Code
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class CodeUtils {
    /**
     * 解析编码路径的工具
     */
    @Nullable
    public static <C extends Code> C parseLocation(String location) throws ClassNotFoundException {
        String[] split = location.split("#");
        Assert.state(split.length == 2, "location must be like 'package-name.code-class-name#enum-name'");
        Class<?> cls = ClassUtils.forName(split[0], null);
        Assert.state(Code.class.isAssignableFrom(cls), "location must be a code instance path");
        Assert.state(cls.isEnum(), "location must be a enum");
        //noinspection unchecked
        Class<? extends Enum<?>> codeCls = (Class<? extends Enum<?>>) cls;
        for (Enum<?> enumConst : codeCls.getEnumConstants()) {
            if (enumConst.name().equals(split[1])) {
                //noinspection unchecked
                return (C) enumConst;
            }
        }
        return null;
    }
}
